import { writeFile, readFile } from 'fs'
import { Request } from 'express'

export function writeFileText(path: string, buff: string): Promise<void> {
  return new Promise((resolve, reject) => {
    writeFile(path, buff, { encoding: 'utf-8' }, (err) => {
      err ? reject() : resolve()
      if (err) {
        throw err
      } else {
        resolve()
      }
    })
  })
}

export function readFileText(path: string): Promise<string> {
  return new Promise((resolve, reject) => {
    readFile(path, { encoding: 'utf-8' }, (err, data) => {
      err ? resolve('{}') : resolve(data)
    })
  })
}

export function getStream(req: Request): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    const arr = []
    let chunks = Buffer.from([])
    req.once('data', (buff) => {
      arr.push(buff)
    })
    req.once('end', () => {
      chunks = Buffer.concat(arr)
      resolve(chunks)
    })
    req.once('error', (err) => {
      reject(chunks)
    })
  })
}

export function jsonToWechatXml(json): string {
  // const demo = {
  //   ToUserName: 'toUser',
  //   FromUserName: 'fromUser',
  //   CreateTime: '12345678',
  //   MsgType: 'text',
  //   Content: '你好',
  // };
  // const example = `<xml>
  // <ToUserName><![CDATA[ovfAXv3RfIX6GCONy2v-g0h7oJ6M]]></ToUserName>
  // <FromUserName><![CDATA[gh_880587159858]]></FromUserName>
  // <CreateTime>12345678</CreateTime>
  // <MsgType><![CDATA[text]]></MsgType>
  // <Content><![CDATA[测试]]></Content>
  // </xml>`;
  const target = json
  const keys = Object.keys(target)
  const arr = []
  arr.push('<xml>')
  keys.forEach((key) => {
    if (key === 'CreateTime') {
      arr.push(`<CreateTime>${target[key]}</CreateTime>`)
    } else {
      arr.push(`<${key}><![CDATA[${target[key]}]]></${key}>`)
    }
  })
  arr.push('</xml>')
  return arr.join('\n')
}
